package protocol;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import pageProcessor.PageProcessorFactory;

public class HTTP implements AsyncServerProtocol<String> {
	public static final String HEADERS = "HEADERS";
	public static final String MESSAGE = "MESSAGE";
	public static final String METHOD = "METHOD";
	public static final String URI = "URI";
	public static final String HTTP_VERSION = "HTTP_VERSION";
	public static final String HTTP_STATUS = "HTTP_STATUS";

	private HTTPRequest fHTTPRequest = null;
	//	private HTTPResponseHeaders fResponseHeaders = null;
	//	private HTTPMSG fRequestMSG = null;
	//private HTTPMSG fResponseMSG = null;
	private HTTPResponse fHTTPResponse = null;
	private String[] fRestrictedRegexps = new String[0];
	private boolean _shouldClose = false;
	private boolean _connectionTerminated = false;

	//private JSONObject fResponseHeaders;

	protected void setfRestrictedRegexps(String[] fRestrictedRegexps) {
		this.fRestrictedRegexps = fRestrictedRegexps;
	}

	/* (non-Javadoc)
	 * @see protocol.ServerProtocol#processMessage(java.lang.Object)
	 */
	@Override
	public final String processMessage(final String msg) {
		fHTTPRequest = new HTTPRequest(msg);

		String uri = fHTTPRequest.getfHTTPHttpRequestHeaders().getfURI();

		if (null == fHTTPRequest.getfHTTPHttpRequestHeaders().getfMethod()) {
			fHTTPResponse = new HTTPResponse(Headers.STATUS_405,
					Headers.HTTP_VERSION, null, "", false);
		} else {
			boolean parsed = false;
			boolean foundRestrictedMatch = false;
			for (String restrictedURI : fRestrictedRegexps) {
				Pattern regex = Pattern.compile(restrictedURI,
						Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE
								| Pattern.COMMENTS | Pattern.MULTILINE);
				Matcher regexMatcher = regex.matcher(uri);
				foundRestrictedMatch = regexMatcher.find();
				if (foundRestrictedMatch) {
					parsed = true;
					fHTTPResponse = new HTTPResponse(Headers.STATUS_403,
							Headers.HTTP_VERSION, null, "", false);
					this._shouldClose = fHTTPResponse
							.is_shouldCloseConnection();
					return fHTTPResponse.toString();
				}
			}
			if (!parsed) {

				String uriNoLeadingSlash = uri.replaceAll("(?imx)^/", "");
				PageProcessorFactory PPF = new PageProcessorFactory();
				//	System.out.println(this.fHTTPRequest);
				fHTTPResponse = PPF.process(this.fHTTPRequest);

				System.out.println(fHTTPResponse);
				this._shouldClose = fHTTPResponse.is_shouldCloseConnection();
				return fHTTPResponse.toString();

			}

			System.out.println(this.toString());
		}
		return null;

	}

	@Override
	public final boolean isEnd(final String msg) {
		return false;
	}

	public String toString() {
		String session = "request:\n" + this.fHTTPRequest.toString();
		session += "\nresponse:\n" + fHTTPResponse.toString();
		return session;
	}

	@Override
	public boolean shouldClose() {
		return _shouldClose;
	}

	@Override
	public void connectionTerminated() {
		_connectionTerminated = true;
	}

}
